import 'package:flutter/material.dart';
import 'package:life_milestones/MS-Model/MS-User.dart';
import 'package:life_milestones/MS-global-url.dart';
import 'package:life_milestones/MS-request.dart';
import 'package:shared_preferences/shared_preferences.dart';
class MSGlobalUserController extends ChangeNotifier {
  static final MSGlobalUserController _instance = MSGlobalUserController._();

  MSGlobalUserController._();

  factory MSGlobalUserController(){
    return _instance;
  }

  SharedPreferences? instance;

  String? userId;

  init() async {
    instance = await SharedPreferences.getInstance();
    token = instance?.get("token") as String?;
    userId = instance?.get("userId") as String?;
  }

  MSUser? _user;
  String? _token;
  String? lang;

  MSUser? get user {
    return _user;
  }

  String? get token => _token;

  set token(String? value) {
    if (value == null) {
      instance?.remove("token");
    } else {
      instance?.setString("token", value);
    }
    _token = value;
  }

  set user(MSUser? value) {
    _user = value;
    if (value == null) {
      instance?.remove("userId");
    } else {
      instance?.setString("userId", value.userId!);
    }
    notifyListeners();
  }


  Future<void> refreshUserInfo() async {
    try {
      var value = await MSRequest().get(
          MSGlobalUrl.userInfo, queryParameters: {"userId": userId});
      if (value["code"] == 0 && value["data"] != null) {
        user = MSUser.fromJson(value["data"]);
      }
    } catch (e) {}
  }

  onLogout() {
    token = null;
    user = null;
  }

  checkIsFirstLogin() {
    var isFirstLogin = instance?.get(user!.userId!) as String?;
    return isFirstLogin == null;
  }

  setIsFirstLogin() {
    instance?.setString(user!.userId!, "NO");
  }

  checkAvatarIsUpdated() {
    var isUpdated = instance?.get("${user!.userId!}AvatarIsUpdated") as String?;
    return isUpdated != null;
  }

  setAvatarIsUpdated() {
    instance?.setString("${user!.userId!}AvatarIsUpdated", "YES");
  }

}